<template>
    <el-button
        :loading="downloadLoading"
        type="primary"
        icon="el-icon-document"
        @click="handleDownload"
    >
        {{ btnText }}
    </el-button>
</template>

<script>
import { parseTime } from '@/utils';

export default {
    name: 'ExportExcel',
    props: {
        header: {
            required: true,
            type: Array,
        },
        list: {
            required: true,
            type: Array,
        },
        filename: {
            type: String,
            default: 'abc',
        },
        autoWidth: {
            type: Boolean,
            default: true,
        },
        bookType: {
            type: String,
            default: 'xlsx',
        },
        filterVal: {
            type: Array,
            required: true,
        },
        btnText: {
            type: String,
            default: '导出',
        },
    },
    data () {
        return {
            downloadLoading: false,
        };
    },
    methods: {
        handleDownload () {
            this.downloadLoading = true;
            import('@/vendor/Export2Excel').then((excel) => {
                const filterVal = this.filterVal;
                const list = this.list;
                const data = this.formatJson(filterVal, list);
                excel.export_json_to_excel({
                    header: this.header,
                    data,
                    filename: this.filename,
                    autoWidth: this.autoWidth,
                    bookType: this.bookType,
                });
                this.downloadLoading = false;
            });
        },
        formatJson (filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => {
                if (j === 'timestamp') {
                    return parseTime(v[j]);
                } else {
                    return v[j];
                }
            }));
        },
    },
};
</script>
